import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/hj_model/cartoon_media_info.dart';
import 'package:xvideos/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:xvideos/hj_page/cartoon_business/cartoon_recommend_logic.dart';
import 'package:xvideos/routers/jump_router.dart';
import 'package:xvideos/tools_base/loading/l_error_widget.dart';
import 'package:xvideos/tools_base/loading/loading_center_widget.dart';
import 'package:xvideos/tools_base/refresh/pull_refresh.dart';

class CartoonRecommendPage extends StatefulWidget {
  final String? mediaId;
  final bool darkStyle;
  final EdgeInsetsGeometry? padding;
  final Function()? tapAction;

  const CartoonRecommendPage({
    super.key,
    this.mediaId,
    this.darkStyle = false,
    this.tapAction,
    this.padding = const EdgeInsets.only(left: 16, right: 16, top: 10),
  });

  @override
  State<CartoonRecommendPage> createState() => _CartoonRecommendPageState();
}

class _CartoonRecommendPageState extends State<CartoonRecommendPage> {
  late CartoonRecommendLogic logic;

  late String tag;

  @override
  void initState() {
    super.initState();
    tag = (widget.mediaId ?? '') + DateTime.now().millisecondsSinceEpoch.toString();
    logic = Get.put(CartoonRecommendLogic(mediaId: widget.mediaId), tag: tag);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<CartoonRecommendLogic>(
      tag: tag,
      builder: (_) {
        if (_.dataList == null) return LoadingCenterWidget();
        if (_.dataList?.isEmpty == true)
          return CErrorWidget(
            retryOnTap: () => _.loadData(showLoading: true),
          );
        return pullYsRefresh(
          onInit: (ctr) => _.refreshCtr = ctr,
          onLoading: (ctr) => _.loadMoreData(),
          enablePullDown: false,
          child: GridView.builder(
            physics: ClampingScrollPhysics(),
            padding: widget.padding,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3,
              mainAxisSpacing: 12,
              crossAxisSpacing: 6,
              childAspectRatio: 111 / 188,
            ),
            itemCount: _.dataList?.length ?? 0,
            itemBuilder: (context, index) {
              CartoonMediaInfo? meidiaInfo = _.dataList?[index];
              return AcgItemWidget(
                info: meidiaInfo,
                tapCallback: () {
                  widget.tapAction?.call();
                  pushToCartoonPage(meidiaInfo);
                },
              );
            },
          ),
        );
      },
    );
  }
}
